package org.ielts.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.ielts.domain.base.Course;
import org.ielts.domain.base.CourseType;
import org.ielts.repository.CourseRepository;
import org.ielts.repository.CourseTypeRepository;
import org.ielts.util.MapListWapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CourseService {

	@Autowired
	CourseRepository courseRepository;

	@Autowired
	CourseTypeRepository courseTypeRepository;

	@Transactional
	public Course createCourse(String name, String title) {
		Course course = new Course();
		course.setName(name);
		course.setTitle(title);

		courseRepository.save(course);

		return course;
	}

	@Transactional
	public Iterable<Course> findAll() {
		return courseRepository.findAll();
	}

	@Transactional
	public Course modifyCourse(String id, String name, String title) {
		Course course = courseRepository.findOne(id);

		course.setTitle(title);
		course.setName(name);

		return course;
	}

	@Transactional
	public void removeCourse(String id) {
		courseRepository.delete(id);
	}

	@Transactional
	public Course findOne(String id) {
		Course course = courseRepository.findOne(id);

		return course;
	}

	@Transactional
	public Course findOneByName(String name) {
		Course course = courseRepository.findOneByName(name);

		return course;
	}

	@Transactional
	public MapListWapper<String, Course> findNameIdMap() {
		Map<String, Course> m = new HashMap<String, Course>();
		Iterable<Course> cs = courseRepository.findAll();
		for (Course c : cs) {
			m.put(c.getName().toLowerCase(), c);
		}
		MapListWapper<String, Course> result = new MapListWapper<String, Course>(m, cs);
		return result;
	}
}
